const baseUrl = process.env.VUE_APP_API

export default function doRequest(options) {
    console.log("ssssssssssssssss")
    console.log(options)
    let url = options.url;
    let method = options.method;
    let params = options.params;
    let data = options.data

    console.log(url)

    let requestUrl = baseUrl + url
    let methodData;
    if (['POST', 'PUT', 'PATCH'].includes(method)) {
        methodData = data
        requestUrl = requestUrl + "?" + serialize(params)
    } else {
        methodData = params
    }

    return new Promise(resolve => {
        console.log("开始请求……")
        console.log(baseUrl + url)
        uni.request({
            method,
            url: requestUrl,
            data: methodData,
            success: (res) => {
                let msg;
                switch (res.statusCode) {
                    case 400:
                        msg = '请求错误';
                        break
                    case 401:
                        msg = '未授权，请登录';
                        break
                    case 403:
                        msg = '拒绝访问';
                        break
                    case 404:
                        msg = `请求地址出错`;
                        break
                    case 408:
                        msg = '请求超时';
                        break
                    case 500:
                        msg = '服务器内部错误';
                        break
                    case 501:
                        msg = '服务未实现';
                        break
                    case 502:
                        msg = '网关错误';
                        break
                    case 503:
                        msg = '服务不可用';
                        break
                    case 504:
                        msg = '网关超时';
                        break
                    case 505:
                        msg = 'HTTP版本不受支持';
                        break
                }
                if (msg) {
                    uni.showToast({
                        title: msg,
                        icon: 'none'
                    })
                    return Promise.reject()
                }
                resolve(res.data[0]);
            }
        })
    })
}


const serialize = function (obj) {
    var str = [];
    for (var p in obj)
        if (obj.hasOwnProperty(p)) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
    return str.join("&");
}
